<template>
    <div id="instructionInfo-content">
        <el-row class="form-content">
            <el-form label-width="70px">
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="产品代码(名称):">
                            <el-select v-model="searchForm.fundCode" size="mini" filterable clearable style="width: 100%">
                                <el-option
                                    v-for="i in fundCodeSelectData"
                                    :key="i.fundCode"
                                    :label="i.fundCode + ' ' + i.fundNameSt"
                                    :value="i.fundCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="证券代码(名称):">
                            <el-select
                                v-model="searchForm.stockCode"
                                filterable
                                :filter-method="getstockCodeList"
                                @visible-change="handleStockVisibleChange"
                                @clear="getstockCodeList('')"
                                clearable
                                size="mini"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="(i, index) in stockCodeSelectData"
                                    :key="i.stockCode + index"
                                    :label="i.stockCode + ' ' + i.stockNameSt"
                                    :value="i.stockCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="委托方向:">
                            <el-select v-model="searchForm.orderDirection" clearable size="mini" style="width: 100%">
                                <el-option v-for="i in orderDirectionData" :key="i.dictKey" :label="i.dictKeyName" :value="i.dictKey"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="证券类别:">
                            <el-select v-model="searchForm.stockType" filterable clearable size="mini" style="width: 100%">
                                <el-option
                                    v-for="(item, index) in stockType"
                                    :key="item.dictKey + index"
                                    :value="item.dictKey"
                                    :label="item.dictKeyName"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="业务类型:">
                            <el-select v-model="searchForm.businessType" clearable size="mini" style="width: 100%">
                                <el-option
                                    v-for="(item, index) in businessTypeSelectData"
                                    :key="item.dictKey + index"
                                    :value="item.dictKey"
                                    :label="item.dictKeyName"
                                ></el-option>

                                <!-- <el-option value="x" label="融资融券信用业务"> </el-option> -->
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="2">
                        <el-button type="primary" size="mini" @click="query">查询</el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="指令序号:">
                            <el-input size="mini" placeholder="" v-model="searchForm.instNo"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="指令状态:">
                            <el-select v-model="searchForm.instStatus" size="mini" style="width: 100%">
                                <el-option v-for="(value, key) in instructionStatus" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <el-form-item label="下达人:">
                            <el-select v-model="searchForm.directUser" filterable clearable size="mini" style="width: 100%">
                                <el-option
                                    v-for="item in orderUsers"
                                    :key="item.dictKey + item.dictCode"
                                    :value="item.dictCode"
                                    :label="item.dictKey + ' ' + item.dictKeyName"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="下达日期:">
                            <el-date-picker
                                v-model="directDate"
                                type="date"
                                placeholder="请选择"
                                value-format="yyyyMMdd"
                                format="yyyy/MM/dd"
                                style="width: 100%"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-button type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
                        <el-button size="mini" @click="handleButtonClick('hide')" v-show="SHOW_SECURITY">{{
                            hideVisible ? '展开' : '隐藏'
                        }}</el-button>
                    </el-col>
                </el-row>
                <el-row v-if="!hideVisible">
                    <el-col :span="5">
                        <el-form-item label="资产单元编号(名称):">
                            <el-select v-model="searchForm.assetCode" filterable clearable size="mini">
                                <el-option
                                    v-for="i in assetCodeSelectData"
                                    :key="i.assetCode"
                                    :label="i.assetCode + ' ' + i.assetName"
                                    :value="i.assetCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="组合编码(名称):">
                            <el-select v-model="searchForm.fundAcCode" filterable clearable size="mini">
                                <el-option
                                    v-for="i in fundAccountCodeSelectData"
                                    :key="i.fundAccountCode"
                                    :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                    :value="i.fundAccountCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-row>
        <el-row class="table-content">
            <div style="height: calc(100% - 60px)">
                <vxe-table
                    :key="tableKey"
                    :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                    :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                    :data="dataSource"
                    border
                    v-loading="tableLoading"
                    element-loading-text="加载中"
                    size="mini"
                    height="100%"
                    ref="table"
                    @cell-click="handleRow"
                    style="cursor: pointer"
                    highlight-current-row
                    highlight-hover-row
                    stripe
                    auto-resize
                    resizable
                    :sort-config="{
                        defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                        remote: true,
                    }"
                    @sort-change="changeTableSort"
                    show-header-overflow
                >
                    <template v-for="(item, index) in showFieldList">
                        <vxe-column
                            show-overflow
                            :key="index + 'name'"
                            :title="item.content"
                            :field="item.id"
                            :min-width="item.minWidth"
                            :width="item.width"
                            :fixed="item.fixed"
                            :sortable="item.id == 'operate' ? false : true"
                        >
                            <template slot="header">
                                <span>{{ item.content }}</span>
                            </template>
                            <template slot-scope="scope">
                                <span v-if="item.id == 'operate'">
                                    <el-button type="text" @click="handleUpdateInst(scope.row)" :disabled="handleDisabled(scope.row)">修改</el-button>
                                    <el-button type="text" @click.stop="handleCancelOrder(scope.row)" :disabled="handleDisabled(scope.row)"
                                        >撤单</el-button
                                    >
                                </span>
                                <span v-else-if="item.id == 'instStatus'">
                                    {{ instructionStatus[scope.row.instStatus] }}
                                </span>
                                <span v-else-if="item.id == 'orderPriceType'">
                                    {{ scope.row.orderPriceType ? investPricePojo[scope.row.orderPriceType] : '--' }}
                                </span>
                                <span v-else-if="item.id == 'stockType'">
                                    {{ scope.row[item.id] ? stockTypePojo[scope.row[item.id]] : '--' }}
                                </span>

                                <span v-else-if="item.id == 'directTime'">
                                    {{ formatterDate(scope.row) }}
                                </span>

                                <span v-else-if="item.id == 'directUserName'">
                                    {{ scope.row.directUserName.trim() ? scope.row.directUserName : '--' }}
                                </span>

                                <span v-else-if="['orderBalance', 'orderAmount', 'orderPrice'].includes(item.id)">
                                    {{ scope.row[item.id] ? numberFormat(scope.row[item.id], 2) : '0' }}
                                </span>

                                <span v-else>{{ scope.row[item.id] && scope.row[item.id].trim() ? scope.row[item.id] : '--' }}</span>
                            </template>
                        </vxe-column>
                    </template>
                </vxe-table>
                <risk-pagination :paging="pages" @page-change="handleCurrentChange"></risk-pagination>
            </div>
        </el-row>
        <el-row class="tab-content">
            <el-tabs v-model="activeKey" style="height: 100%">
                <el-tab-pane label="指令明细" name="detail" class="inst-detail">
                    <div class="detail-container" :key="tabskey + 'tabskey'">
                        <InstructionDetail :key="detailKey" :detailFields="detailFields" :instructionInfo="instDetailData" :noData="noData" />
                    </div>
                </el-tab-pane>
                <el-tab-pane label="指令证券" name="stock">
                    <div style="height: 100%; padding: 4px 10px">
                        <risk-table :msg="instStockMsg" v-loading="tabsLoading"></risk-table>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="指令质押券" name="pledge">
                    <div style="height: 100%; padding: 4px 10px">
                        <risk-table :msg="instPledgeMsg" v-loading="tabsLoading"></risk-table></div
                ></el-tab-pane>

                <el-tab-pane label="指令结果" name="result">
                    <div style="height: 100%; padding: 4px 10px">
                        <risk-table
                            :msg="instResultMsg"
                            v-loading="tabsLoading"
                            @handleBtn="handleBtnLook"
                            :key="instResultMsgNumKey + 'instResultMsgNumKey'"
                            v-if="activeKey === 'result'"
                        ></risk-table></div
                ></el-tab-pane>
            </el-tabs>
        </el-row>

        <yh-dialog drag title="撤单确认" :close-on-click-modal="false" :before-close="closeDialog" :visible="cancelDialog" width="600px">
            <el-form v-model="cancelOrder" label-width="90px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="指令批号">
                            <el-input v-model="batchNo" size="mini" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="指令序号">
                            <el-input v-model="cancelOrder.instNo" disabled size="mini"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="撤单人">
                            <el-input v-model="cancelOrder.tradeUserName" disabled size="mini"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="撤单方式">
                            <el-select v-model="cancelOrder.cancelOrderType" size="mini">
                                <el-option key="1" value="1" label="指令序号"></el-option>
                                <el-option key="2" value="2" label="指令批号"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="handleSubmit">确 定</el-button>
            </span>
        </yh-dialog>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="BATCH_INST_INFO"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import Invest from '@/common/dict/invest';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { dateFormat, numberFormat, unitShow, timeFormat, UUID, sortBy, getConfigItem } from '@/utils/tools';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import ColumnUtil from '../utils/column-util';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import RiskTable from '@/common/components/risk-table.vue';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import InstructionDetail from '../components/instruction-detail.vue';
import InstructionInfoClass from '../class/instruction-info-class';
import RiskPagination from '@/common/components/risk-pagination.vue';
import InstructionColumnUtil from '@/pages/report/instruction-query/instruction-column-util';
import XEUtils from 'xe-utils';
import BatchColumnUtil from '../utils/batch-column-util';
import { getUser } from '@/utils/user-util';

@Component({
    name: 'BatchOrderInfo',
    components: {
        RiskTableLayout,
        RiskTable,
        StatusTag,
        RiskEntryInput,
        InstructionDetail,
        RiskPagination,
    },
})
// 融资融券指令管理tab
export default class BatchOrderInfo extends InstructionInfoClass {
    @Prop()
    renderCount: number;
    Invest: any = new Invest();
    timeFormat = timeFormat;
    dateFormat = dateFormat;
    numberFormat = numberFormat;
    InstructionColumnUtil = new InstructionColumnUtil();
    BatchColumnUtil = new BatchColumnUtil();
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');

    instructionStatus = {
        '0': '已归档',
        '1': '已下达成功',
        '3': '已撤销',
        // '2': '已归档',
    };

    // 查询表单
    searchForm: any = {
        businessType: '',
        directUser: '',
        fundCode: '',
        instNo: '',
        instStatus: '1',
        orderDirection: '',
        stockCode: '',
        stockType: '',
        assetCode: '',
        fundAcCode: '',
    };

    queryForm: any = {
        bankBondAssetTypes: [],
        bankBondMarketTypes: [],
        businessTypes: [],
        depositStockTypes: [],
        directUsers: [],
        exchangeAssetTypes: [],
        exchangeMarketTypes: [],
        exchangeStockTypes: [],
        fundCodes: [],
        instNo: '',
        instStatus: '1',
        orderDirections: [],
        outOrderCode: '',
        paging: {
            pageSize: 50,
            currentPage: 1,
        },
        stockCodes: [],
        stockTypes: [],
        userCode: '',
        sourceType: [],
        batchType: '1',
        assetCode: '',
        fundAcCode: '',
    };

    directDate: string = '';
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundCodeWithPermission: any[] = []; // 根据权限查询的产品
    fundCodeWithAssetUnit: any[] = []; // 包含资产单元为融资融券信用资产单元的基金列表
    businessTypeSelectData: any[] = [];
    // 委托方向数据
    orderDirectionData: any[] = [];
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    orderUsers: any[] = []; // 下单人下拉列表
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    tabskey: number = -1;
    stockType: any[] = []; // 证券类别下拉
    dataSource: any[] = []; // 指令表数据
    stockTypeAll: any[] = []; // 证券类别

    // 指令信息表格固定字段
    fixedFieldList: any[] = [
        { content: '指令序号', id: 'instructionNo', fixed: 'left', minWidth: 120 },
        { content: '指令批号', id: 'batchNo', minWidth: 120, fixed: 'left' },
        { content: '产品编码', id: 'fundCode', fixed: 'left', minWidth: 120 },
        { content: '指令状态', id: 'instStatus', fixed: 'right', minWidth: 120 },
        { content: '操作', id: 'operate', fixed: 'right', minWidth: 120 },
    ];

    // 全部表格列
    tableColumns: any[] = [
        { content: '指令序号', id: 'instructionNo', minWidth: 120, fixed: 'left' },
        { content: '指令批号', id: 'batchNo', minWidth: 120, fixed: 'left' },
        { content: '产品编码', id: 'fundCode', minWidth: 120, fixed: 'left' },
        { content: '产品名称', id: 'fundName', minWidth: 120 },
        { content: '组合编码', id: 'fundAccountCode', minWidth: 150 },
        { content: '组合名称', id: 'fundAccountName', minWidth: 150 },
        { content: '证券代码', id: 'stockCode', minWidth: 120 },
        { content: '证券名称', id: 'stockName', minWidth: 120 },
        { content: '证券类别', id: 'stockTypeName', minWidth: 120 },
        { content: '业务类型', id: 'businessTypeName', minWidth: 120 },
        { content: '委托方向', id: 'orderDirection', minWidth: 120 },
        { content: '投资类型', id: 'investType', minWidth: 120 },
        { content: '币种', id: 'curName', minWidth: 120 },
        { content: '交易市场', id: 'marketName', minWidth: 120 },
        { content: '下达人', id: 'directUserName', minWidth: 100 },
        { content: '下达时间', id: 'directTime', minWidth: 120 },
        { content: '指令状态', id: 'instStatus', minWidth: 120, fixed: 'right' },
        { content: '操作', id: 'operate', minWidth: 120, fixed: 'right' },
    ];
    selectedFieldList: any[] = []; // 已选择字段列表(不包括固定字段)
    showFieldList: any[] = []; // 要显示的表格列
    layoutDialog: boolean = false; // 布局设置弹框显示

    // 指令明细字段
    detailFields: any[] = [];

    // 指令证券表格相关
    instStockMsg: any = {
        returnData: { list: [] },
        dataKey: 'list',
        title: [],
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };
    instPledgeMsg: any = {
        returnData: {},
        dataKey: 'list',
        title: [],
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };

    activeKey: string = 'detail'; //  指令当前tabKey
    tableKey: number = 0;

    clickRecord: any = {}; // 当前主表格点击的条目
    rowClickSetTime = null;
    instructionDetail: any = {};
    instStockDataSource: any[] = []; // 指令证券表数据
    instPledgeDataSource: any[] = []; // 指令质押券表数据
    instResultDataSource: any[] = []; // 指令结果表数据
    type: string = '';

    commonField = this.ColumnUtil.commonFieldSort;
    extraField: any = {};
    marketCodes: any = {};
    isShowTooltip: boolean = false;

    noData: boolean = true; // 是否有指令数据
    instructionInfoUrl: string = '/comprehensive/inst/query';
    instDetailData: any = {}; // 指令明细
    // 明细中默认展示字段
    defaultFieldsReal: any[] = [];
    defaultFields: any[] = this.InstructionColumnUtil.defaultDetailColumn;
    fileds: any[] = []; // 根据指令类型展示拼接字段
    hasClick: boolean = false; // 是否已点击
    orderDirectionPojo: any = {};
    orderDirectionMapping: any = {};
    stockInfo: any = {};
    investPricePojo: any = {};
    cancelDialog: boolean = false;
    batchNo: string = '';
    delRow: any = {};

    // 撤单表单
    cancelOrder: any = {
        cancelOrderType: '1',
        tradeUser: getUser().userCode, // 当前用户
        tradeUserName: getUser().userName, // 当前用户
        orderType: '4',
        instructionType: '10',
        instNo: '',
        originOuterOrderCode: '',
        outerOrderCode: UUID() + '-' + new Date().getTime(),
        requestId: UUID() + '-' + new Date().getTime(),
    };

    @Watch('renderCount')
    onWatchRenderCount() {
        this.getInstruction(this.queryForm, this.pages);
    }

    hideVisible: boolean = true; // 是否隐藏
    assetCodeSelectData: any[] = [];
    fundAccountCodeSelectData: any[] = [];
    async mounted() {
        if (this.SHOW_SECURITY) {
            this.$axios.get('/asset/list/byFundCode').then((res: any) => {
                this.assetCodeSelectData = res;
            });
            this.$axios.get('/fdAc/list/byFundCode').then((res: any) => {
                this.fundAccountCodeSelectData = res;
            });
        }
        this.tableColumns = this.ColumnUtil.handleTableColumns(this.tableColumns, 'id');
        this.defaultFieldsReal = XEUtils.clone(this.defaultFields, true);
        // 获取证券代码下拉框数据
        this.getstockCodeList('');
        // 下单人下拉列表
        this.$axios.post('instruction/user/select').then((res: any) => {
            this.orderUsers = res;
        });

        let columns = this.ColumnUtil.instStockColumns;
        columns.splice(1, 0, { name: '指令批号', val: 'batchNo', minWidth: 120 });
        this.instStockMsg.title = columns;
        let pledgeColumns = this.ColumnUtil.instPledgeColumns;
        pledgeColumns.splice(1, 0, { name: '指令批号', val: 'batchNo', minWidth: 120 });
        this.instPledgeMsg.title = pledgeColumns;

        // 证券类别
        this.stockTypeAll = await DictionConstUtil.FNStockType();
        this.stockTypePojo = DictionConstUtil.ListToPojo(await DictionConstUtil.FNStockType());
        // 价格模式
        let priceTypeTemp = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
        this.investPricePojo = DictionConstUtil.ListToPojo(priceTypeTemp);

        this.getBusinessType();
        this.queryLayout();
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);
        this.marketCodes = DictionConstUtil.ListToPojo(await DictionConstUtil.FNMarketType());
        this.stockType = await DictionConstUtil.FNStockType();
        this.orderDirectionData = await DictionConstUtil.FNTradeDirection();
        // 获取所有订单方向
        this.orderDirectionPojo = DictionConstUtil.ListToPojo(await SGU_CACHE('TradeDirection', '/dict/tradeDirections', []));
        this.orderDirectionMapping = DictionConstUtil.ReversePojo(this.orderDirectionPojo);
    }

    query() {
        this.getQueryForm();
        if (this.directDate) {
            this.queryForm.directDate = Number(this.directDate);
        }
        this.clickRecord = {};
        this.getInstruction(this.queryForm, { currentPage: 1, pageSize: 50 });
    }

    // 按钮点击
    handleButtonClick(action: string): void {
        if (action === 'hide') {
            this.hideVisible = !this.hideVisible;
            console.log(this.hideVisible, 'hideVisible');
        }
    }

    // 获取查询表单
    getQueryForm() {
        for (const key in this.searchForm) {
            if (['businessType', 'directUser', 'fundCode', 'orderDirection', 'stockCode', 'stockType'].includes(key)) {
                if (this.searchForm[key]) {
                    this.queryForm[key + 's'] = [this.searchForm[key]];
                } else {
                    this.queryForm[key + 's'] = [];
                }
            }
        }
        this.queryForm.instStatus = this.searchForm.instStatus;
        this.queryForm.instNo = this.searchForm.instNo;
        this.queryForm.assetCode = this.searchForm.assetCode;
        this.queryForm.fundAcCode = this.searchForm.fundAcCode;
    }

    // 指令信息表格分页
    handleCurrentChange(): void {
        this.getQueryForm();
        this.getInstruction(this.queryForm, this.pages);
    }

    // 排序改变
    changeTableSort(column: any): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        if (sortType) {
            this.queryForm.sort = this.findName(column.property, sortType);
        } else {
            this.queryForm.sort = 'D_DIRECT_DATE ' + 'DESC' + ',' + 'D_DIRECT_TIME ' + 'DESC';
        }
        this.getQueryForm();
        this.getInstruction(this.queryForm, this.pages);
    }

    // 获取排序字段名称
    findName(name: string, order: string): string {
        let value = '';
        let field = '';
        let allFields = { ...this.commonField, ...this.ColumnUtil.fundTransferFieldSort, stockTypeName: 'C_STOCK_TYPE' };
        if (name === 'directTime') {
            value = 'D_DIRECT_DATE' + ' ' + order + ',' + 'D_DIRECT_TIME' + ' ' + order;
        } else {
            for (const key in allFields) {
                if (name === key) {
                    field = allFields[key];
                }
            }
            value = field + ' ' + order;
        }
        return value;
    }

    handleCancelOrder(row: any) {
        this.delRow = row;
        this.batchNo = row.batchNo;
        this.cancelOrder.instNo = row.instructionNo;
        this.cancelOrder.originOuterOrderCode = row.outOrderCode;
        this.cancelDialog = true;
    }

    handleSubmit() {
        if (this.cancelOrder.cancelOrderType == '1') {
            this.cancelOrder.serialNo = this.delRow.serialNo;
        } else {
            delete this.cancelOrder.serialNo;
        }
        this.handleBtnDel();
    }

    closeDialog() {
        // 撤单表单重置
        this.cancelOrder = {
            cancelOrderType: '1',
            tradeUser: getUser().userCode, // 当前用户
            tradeUserName: getUser().userName, // 当前用户
            orderType: '4',
            instructionType: '10',
            instNo: '',
            originOuterOrderCode: '',
            outerOrderCode: UUID() + '-' + new Date().getTime(),
            requestId: UUID() + '-' + new Date().getTime(),
        };
        this.cancelDialog = false;
    }

    // 撤单事件
    handleBtnDel(): void {
        // this.cancelOrder.instNo = row.instructionNo;
        // this.cancelOrder.originOuterOrderCode = row.outOrderCode;
        // this.cancelOrder.serialNo = row.serialNo;
        this.$axios
            .post('/dataEngine/order/cancelOrder', this.cancelOrder)
            .then((res: any) => {
                this.yh_message_success('撤单成功');
                this.getInstruction(this.queryForm, { currentPage: 1, pageSize: this.pages.pageSize });
                this.closeDialog();
            })
            .catch(() => {
                this.yh_message_error('撤单失败');
            });
    }

    getInstruction(param: any, pages: any) {
        this.tableLoading = true;
        this.$axios
            .post(this.instructionInfoUrl, {
                ...this.queryForm,
                paging: {
                    currentPage: pages.currentPage,
                    pageSize: pages.pageSize,
                },
            })
            .then((res: any) => {
                this.dataSource = res.list;
                this.pages.total = res.total;
                if (this.dataSource.length) {
                    this.currentClickRow = this.dataSource[0] || {};
                    if (this.currentClickRow.instStatus == '0') {
                        this.type = 'history';
                    } else {
                        this.type = '';
                    }
                    (this.$refs['table'] as any).setCurrentRow(this.dataSource[0]);
                    this.handleRow({ row: this.currentClickRow });
                    this.noData = false;
                } else {
                    this.$set(this.instStockMsg.returnData, 'list', []);
                    this.$set(this.instResultMsg.returnData, 'list', []);
                    this.noData = true;
                }
                this.tableLoading = false;
            })
            .catch(() => {
                this.tableLoading = false;
            });
    }

    getBusinessType() {
        this.$axios.get('/dict/businessType/all').then((res: any) => {
            this.businessTypeSelectData = res;
        });
    }

    // 获取证券代码下拉框数据
    async getShFixedStockCodeList(e: string) {
        await this.$axios
            .post('/dict/stock/select/' + 2, {
                dictKey: e,
                dictKeyName: e,
            })
            .then((res: any) => {
                if (res && res.length) {
                    this.stockInfo = res[0];
                }
            });
    }

    // 获取证券代码下拉框数据
    getstockCodeList(value: string) {
        this.selectLoading = true;
        this.$axios
            .post('/original/stock/list', {
                paging: {
                    currentPage: 1,
                    pageSize: 20,
                },
                stockCode: value,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res.list || [];
                this.selectLoading = false;
            });
    }

    handleStockVisibleChange(val) {
        if (!val) {
            this.getstockCodeList('');
        }
    }

    // 格式化日期
    formatterDate(row: any) {
        let date = dateFormat(row.directDate);
        let time = timeFormat(row.directTime);
        let dateTime = date + ' ' + time;
        return dateTime.trim() ? dateTime : '--';
    }

    // 修改指令
    handleUpdateInst(row: any) {
        setTimeout(() => {
            this.$emit('changeTab', this.instDetailData);
        }, 100);
    }

    // 查看按钮点击
    handleBtnLook(obj: any): void {
        this.$emit('handelOperate', { record: obj.row, history: this.type === 'history', clickRecord: this.clickRecord });
    }

    // 点击单行
    async handleRow({ row }) {
        this.clickRecord = JSON.parse(JSON.stringify(row));
        this.currentClickRow = JSON.parse(JSON.stringify(row));
        if (this.orderDirectionMapping[row?.orderDirection]) {
            row.orderDirectionCode = this.orderDirectionMapping[row?.orderDirection];
        }
        this.hasClick = true;
        this.handleJudgeInst(row);
        // let data: any = {};
        this.instDetailData = JSON.parse(JSON.stringify(row));
        this.instDetailData.instStatus = this.instructionStatus[this.instDetailData.instStatus];
        if (this.instDetailData?.priceType) {
            this.instDetailData.priceType = this.investPricePojo[this.instDetailData.priceType];
        }
        if (this.clickRecord.businessType === 'I') {
            await this.getShFixedStockCodeList(this.instDetailData.stockCode);
            // 应计利息
            let interest = this.calcInterest(this.instDetailData.instAmount, this.stockInfo.tDayInterest);
            // 全价价格
            this.instDetailData.fullPrice = this.calcFullPrice(this.instDetailData.instPrice, this.stockInfo.tDayInterest);
            // 总应计利息
            this.instDetailData.totalInterest = interest.toString();
            // 全价金额
            this.instDetailData.fullBalance = (Number(this.instDetailData.instBalance) + Number(this.instDetailData.totalInterest)).toFixed(2);
        }
        this.getInstructionInfo();
    }

    // 根据业务类型显示不同的指令明细字段
    handleJudgeInst(row) {
        let businessType: string = '';
        switch (row.businessType) {
            case '1':
                this.detailFields = this.BatchColumnUtil.exchangeDetailFields;
                if (['l', '98'].includes(row.orderDirectionCode)) {
                    this.detailFields = this.BatchColumnUtil.refinanceDetailFields;
                }
                break;
            case '2':
                if (['3', '4'].includes(row.orderDirectionCode)) {
                    this.detailFields = this.BatchColumnUtil.bondDetailFields;
                } else if (['5', '6'].includes(row.orderDirectionCode)) {
                    this.detailFields = this.BatchColumnUtil.buybackDetailFields;
                }
                break;
            case '4':
                this.detailFields = this.BatchColumnUtil.futrueGoodsDetailFields;
                break;
            case '6':
                this.detailFields = this.BatchColumnUtil.exchangeDetailFields;
                break;
            case 'A':
                this.detailFields = this.BatchColumnUtil.cwDetailFields;
                break;
            case 'B':
                this.detailFields = this.BatchColumnUtil.depositDetailFields;
                break;
            case 'C':
                this.detailFields = this.BatchColumnUtil.purchaseDetailFields;
                break;
            case 'D':
                // 只有产品代码
                this.detailFields = this.BatchColumnUtil.primaryBondDetailFields;
                break;
            case 'E':
                this.detailFields = this.BatchColumnUtil.exchangeBulkDetailFields;
                break;
            case 'I':
                this.detailFields = this.BatchColumnUtil.shFixedDetailFields;
                break;
            default:
                break;
        }
        this.detailFields = this.ColumnUtil.handleDetailFieldsOnSecurity(
            this.detailFields,
            true,
            this.ColumnUtil.otherAssetColumns,
            'id',
            'fundNameSt'
        );
    }

    // 查询指令证券和指令结果
    getInstructionInfo() {
        let detailQuery = {
            historyDate: this.clickRecord.historyDate || 0,
            instClass: this.clickRecord.instClass || '',
            instNo: this.clickRecord.instructionNo || '',
            instStatus: this.clickRecord.instStatus || '',
            outOrderCode: this.clickRecord.outOrderCode || '',
            serialNo: this.clickRecord.serialNo || 0,
            userCode: '',
        };
        this.tabsLoading = true;
        this.$axios
            .post('/comprehensive/inst/detail', detailQuery)
            .then((response: any) => {
                let res = response.instructionAllResult;
                if (res) {
                    // 指令证券
                    let instStockDataSource = [];
                    // 业务类型为"融资融券信用业务"
                    if (this.clickRecord.businessType === 'x') {
                        instStockDataSource = res.rzrqStocks;
                    } else if (this.clickRecord.instClass == '6') {
                        instStockDataSource = res.securityLoans;
                        instStockDataSource.forEach((item, i) => {
                            item.instPrice = item.instAmount ? item.instBalance / item.instAmount : '0';
                        });
                    } else {
                        if (res.deposits && res.deposits.length > 0) {
                            instStockDataSource = instStockDataSource.concat(res.deposits);
                        }
                        if (res.repos && res.repos.length > 0) {
                            instStockDataSource = instStockDataSource.concat(res.repos);
                        }
                        if (res.stocks && res.stocks.length > 0) {
                            instStockDataSource = instStockDataSource.concat(res.stocks);
                        }
                        if (this.clickRecord.instClass === '4' && this.clickRecord.sourceType === '2') {
                            instStockDataSource.forEach(ele => {
                                ele.instPrice = Number(ele.instPrice || '0') * 100;
                            });
                        }
                    }

                    instStockDataSource.forEach((item, i) => {
                        item.key = item.serialNo + '-' + i;
                        item.stockCode = this.clickRecord.stockCode;
                        item.stockNameSt = this.clickRecord.stockName;
                        item.marketCode = this.clickRecord.marketName;
                    });

                    this.$set(this.instStockMsg.returnData, 'list', instStockDataSource);

                    if (res.results && res.results.length > 0) {
                        res.results.forEach((item, i) => {
                            item.key = item.entryCode + '-' + i;
                            item.stockCode = this.clickRecord.stockCode;
                        });
                        res.results = res.results.sort(sortBy('thresholdType', 'desc'));
                    }
                    this.$set(this.instResultMsg.returnData, 'list', res.results || []);
                    //  res.results.filter(item => item.thresholdType != '4')

                    let instPledgeDataSource = res.pleds;
                    // 处理质押券数据
                    instPledgeDataSource.forEach(ele => {
                        // 交易市场
                        ele.marketName = this.marketCodes[ele.marketCode];
                        // 券面总额
                        ele.totalFacePrice = ele.totalFacePrice / 10000;
                        // 成交金额
                        ele.balance = (ele.totalFacePrice * ele.pledgeRate) / 100;
                    });
                    this.$set(this.instPledgeMsg.returnData, 'list', instPledgeDataSource);
                }
                if (response.instructionDetail) {
                    this.instDetailData = Object.assign(this.instDetailData, response.instructionDetail);
                    this.instDetailData.instStatus = this.instructionStatus[this.instDetailData.instStatus];
                    this.instDetailData.opponentCode = this.clickRecord.opponentCode;
                    this.instDetailData.opponentName = this.clickRecord.opponentName;
                    this.instDetailData.stockType = this.stockTypePojo[this.instDetailData.stockType];
                }
                this.tabskey++;
                this.tabsLoading = false;
            })
            .catch(() => {
                this.tabskey++;
                this.tabsLoading = false;
            });
    }

    async onSubmit(data) {
        await this.queryLayout();
    }

    /**
     * 应计利息 = 指令数量 *T日百元利息
     */
    calcInterest(orderAmount, tDayInterest) {
        let result = Number(orderAmount) * Number(tDayInterest || 0);
        return result;
    }

    /**
     * 全价价格计算公式 全价价格=净价价格+T日百元利息(最新计算逻辑)
     */
    calcFullPrice(orderPrice, interest) {
        let result = String((Number(orderPrice || 0) + Number(interest || 0)).toFixed(2));
        if (result === 'NaN' || result === 'Infinity') {
            return '0';
        } else {
            return result;
        }
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/BATCH_INST_INFO')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
            this.tableKey++;
        } else {
            this.showFieldList = this.tableColumns;
            this.selectedFieldList = this.tableColumns;
            this.tableKey++;
        }
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/inst-info';
</style>
